<template>
  <div id='Users'>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 面包屑导航区域 -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <!-- 搜索区域 -->
        <el-col :span="9">
          <div class="grid-content bg-purple">
            <el-input placeholder="请输入内容" clearable v-model="queryUserInfo.query" @keyup.enter.native="getUsersList"
              @clear="getUsersList">
              <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
            </el-input>
          </div>
        </el-col>
        <!-- 添加按钮区域 -->
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="usersList" style="width: 100%" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="在线状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeSta(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-slot="scope">
          <template>
            <el-row>
              <el-tooltip class="item" effect="dark" content="编辑" placement="top" :hide-after="2000" :enterable="false">
                <el-button type="primary" icon="el-icon-edit" size="small" @click="writeDialog(scope.row.id)">
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="top" :hide-after="2000" :enterable="false">
                <el-button type="danger" icon="el-icon-delete" size="small" @click="removeUser(scope.row.id)">
                </el-button>
              </el-tooltip>
              <!-- 分配权限的相关设置 -->
              <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :hide-after="2000"
                :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size="small" @click="allotUser(scope.row)"></el-button>
              </el-tooltip>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryUserInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryUserInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-card>
    <!-- 对话框区域 -->
    <!-- 添加用户对话框区域 -->
    <el-dialog title="添加用户信息" :visible.sync="addDialogVisible" width="30%" @close="clearAdd">
      <el-form :model="addForm" :rules="FormRules" ref="addFormRef" label-width="55px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model.trim="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model.trim="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="号码" prop="mobile">
          <el-input v-model.trim="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 控制编写用户对话框的区域 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="30%" @close="clearedit">
      <el-form :model="editForm" :rules="FormRules" ref="editFormRef" label-width="55px">
        <el-form-item label="姓名" prop="username">
          <el-input :value="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="号码" prop="mobile">
          <el-input v-model.trim="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUsers(editForm.id)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分配用户权限 -->
    <el-dialog title="修改用户信息" :visible.sync="allotDialogVisible" width="30%" @close="cleanRallotUserList">
      <p>用户姓名:{{ allotUserList.username }}</p>
      <p>用户角色:{{ allotUserList.role_name }}</p>
      <p>角色列表:
        <el-select v-model="selectRoleId" placeholder="请选择" size="mini">
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureAllotRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
export default {
  name: 'Users',
  data() {
    // 邮箱的验证规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱'))
    }
    // 手机的验证规则
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^1[3456789]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号码'))
    }
    return {
      selectRoleId: '',
      roleList: [],
      // 分配权限列表
      allotUserList: {},
      editForm: {},
      queryUserInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      usersList: [],
      total: 0,
      // 控制添加用户对话框的显示隐藏
      addDialogVisible: false,
      // 控制编写用户对话框的显示隐藏
      editDialogVisible: false,
      allotDialogVisible: false,
      // 添加用户提交的数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 表单验证规则
      FormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, message: '长度在 3 个字符以上', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async sureAllotRoles() {
      if (!this.selectRoleId) return this.$message.error('请选择用户角色')
      const { meta } = await this.$http.put(`users/${this.allotUserList.id}/role`, { rid: this.selectRoleId })
      if (meta.status !== 200) return this.$message.error('用户角色更改失败')
      this.$message.success('用户角色更改成功')
      this.getUsersList()
      this.allotDialogVisible = false
    },
    cleanRallotUserList() {
      this.cleaRallotUserList = {}
      this.selectRoleId = ''
    },
    // 刷新获取用户列表数据
    async getUsersList() {
      const List = await this.$http.get('users', { params: this.queryUserInfo })
      console.log(List)
      if (List.meta.status !== 200) return this.$message.error('用户数据列表更新错误')
      const { users: userList, total } = List.data
      this.usersList = userList
      this.total = total
    },
    // 更改分页条数
    handleSizeChange(val) {
      this.queryUserInfo.pagesize = val
      console.log(`每页 ${val} 条`)
      this.getUsersList()
    },
    // 更改分页数
    handleCurrentChange(val) {
      this.queryUserInfo.pagenum = val
      console.log(`当前页: ${val}`)
      this.getUsersList()
    },
    // 更改用户状态
    async changeSta(userInfo) {
      const newUserInfo = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (newUserInfo.meta.status !== 200) {
        newUserInfo.meta.status = !newUserInfo.meta.status
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success(newUserInfo.meta.msg)
    },
    // 关闭表单清空数据
    clearAdd() {
      this.$refs.addFormRef.resetFields()
    },
    clearedit() {
      this.editForm = {}
      this.$refs.editFormRef.resetFields()
    },
    // 对表单的再次验证
    addUsers() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('表单数据验证失败,请重新输入')
        const res = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('表单数据提交失败')
        this.$message.success('添加用户成功')
        this.getUsersList()
        this.addDialogVisible = false
      })
    },
    // 删除用户
    async deleteUser(id) {
      const res = await this.$http.delete(`users/${id}`)
      if (res.meta.status === 400) return this.$message.error(res.meta.msg)
      if (res.meta.status !== 200) return this.$message.error('用户删除失败')
      this.$message.success('用户删除成功')
      this.getUsersList()
    },
    async writeDialog(id) {
      const res = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取信息失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改分配用户权限
    async allotUser(userInfo) {
      this.allotUserList = userInfo
      const { data, meta } = await this.$http.get('roles')
      if (meta.status !== 200) return this.$message.error('角色列表获取失败,请稍后再试')
      this.roleList = data
      this.allotDialogVisible = true
    },
    // 修改用户信息
    editUsers(id) {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('表单数据验证失败,请重新输入')
        const res = await this.$http.put(`users/${id}`, this.editForm)
        if (res.meta.status !== 200) return this.$message.error('用户更新失败!')
        this.$message.success('用户信息更新成功')
        this.getUsersList()
        this.editForm = {}
        this.editDialogVisible = false
      })
    },
    // 弹窗询问删除数据
    removeUser(id) {
      this.$confirm('确定要删除这条数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(id)
        this.deleteUser(id)
      }).catch(() => {
        this.$message('已取消删除')
      })
    }
  },
  mounted() {
    this.getUsersList()
  }
}
</script>

<style lang="less" scoped>
/deep/.el-table td.el-table__cell,
.el-table th.el-table__cell.is-leaf {
  border-bottom: 2px solid #d0d2d7;
}

/deep/.el-breadcrumb {
  margin: 0 0 15px 0;
}

/deep/.el-card {
  box-shadow: 0 0 10px #add5e8 !important;
}

/deep/.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell {
  background: #dbf1fb;
}

/deep/.el-table.el-table--fit.el-table--striped.el-table--border.el-table--enable-row-hover.el-table--enable-row-transition {
  margin-top: 15px;
  font-size: 14px;
}

p {
  margin: 10px 0;
}
</style>
